package com.gx.server.model.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gx.server.common.ErrorCode;
import com.gx.server.exception.BusinessException;
import com.gx.server.mapper.UserMapper;
import com.gx.server.model.domain.User;
import com.gx.server.model.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.apache.commons.lang3.StringUtils;


import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Dobby
 * @version 1.0
 */
@Service
@Slf4j
public class UserServiceImpl  extends ServiceImpl<UserMapper,User> implements UserService {


    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "Gx";

    @Override
    public User userRegister(String userAccount, String userPassword, String userEmail, String authCode) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, userEmail, authCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 ) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!authCode.equals("8888")){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内测码错误");
        }

        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";

        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能包含特殊字符");
        }

        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }

        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setPassword(encryptPassword);
        user.setEmail(userEmail);
        user.setIsActive(1);
        user.setLastLogin(LocalDateTime.now());
//        user.setUsername("默认用户");
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "注册失败");

        }

        User user_new = this.userById(user.getId());

        return user_new;
    }


    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户密码为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户长度错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度错误");

        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户格式错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("password", encryptPassword);
        User user = this.getOne(queryWrapper);

        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户密码错误");
        }
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);

        //用户最后登录
        safetyUser.setLastLogin(LocalDateTime.now());

        return safetyUser;
    }


    /**
     * 用户脱敏
     *
     * @param originUser
     * @return
     */
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        return safetyUser;
    }


    /**
     * 修改用户基础信息(名字，邮箱
     * @param loginUser_id
     * @param newUser
     * @return
     */
    @Override
    public boolean updateUser(Long loginUser_id, User newUser) {
        User oldUser = this.getById(loginUser_id);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"未找到用户");
        }
        oldUser.setUsername(newUser.getUsername());
        oldUser.setEmail(newUser.getEmail());

        return this.updateById(oldUser);
    }



    @Override
    public User userById(Long userId) {

        User user = this.getById(userId);

        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户密码错误");
        }
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);
        return safetyUser;
    }


}
